package com.dk.service.impl;

import com.dk.Vo.UUserVo;
import com.dk.mapper.RoleUserMapper;
import com.dk.mapper.UUserMapper;
import com.dk.pojo.RoleUser;
import com.dk.pojo.RoleUserExample;
import com.dk.pojo.UUser;
import com.dk.pojo.UUserExample;
import com.dk.service.UUserServiceI;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UUserServiceImpl implements UUserServiceI {


    //用户表
    @Autowired
    private UUserMapper uUserMapper;

    //角色用户表
    @Autowired
    private RoleUserMapper roleUserMapper;

    @Override
    public PageInfo<UUserVo> getInfoServer(Integer pageNum, Integer pageSize,String uname,Integer depId) {
        PageHelper.startPage(pageNum,pageSize);
        List<UUserVo> list = uUserMapper.getInfoServer(uname,depId);
        PageInfo<UUserVo> page = new PageInfo<>(list);
        return page;
    }

    @Override
    public void addById(UUser uUser, Integer[] rid) {
        uUser.setPassword("123");
        //用户增加并返回ID
        int i = uUserMapper.addById(uUser);

        //增加用户角色中间表
        List<RoleUser> roleUsers = new ArrayList<>();
        for (Integer rids : rid){
            RoleUser roleUser = new RoleUser();
            roleUser.setUid(uUser.getUid());
            roleUser.setRid(rids);
            roleUsers.add(roleUser);
        }
        int j = roleUserMapper.insertBatch(roleUsers);
    }

    @Override
    public UUser getById(Integer uid) {
        return uUserMapper.selectByPrimaryKey(uid);
    }

    @Override
    public void updateById(UUser uUser, Integer[] rid) {

        //用户根据id修改
        uUserMapper.updateByPrimaryKeySelective(uUser);

        //根据用户id 条件删除中间表
        RoleUserExample example = new RoleUserExample();
        RoleUserExample.Criteria criteria = example.createCriteria();
        criteria.andUidEqualTo(uUser.getUid());
        roleUserMapper.deleteByExample(example);

        //重新增加中间表数据
        List<RoleUser> roleUsers = new ArrayList<>();
        for (Integer rids : rid){
            RoleUser roleUser = new RoleUser();
            roleUser.setUid(uUser.getUid());
            roleUser.setRid(rids);
            roleUsers.add(roleUser);
        }
        int j = roleUserMapper.insertBatch(roleUsers);
    }

    @Override
    public void deleteById(Integer uid) {

        //根据用户id 进行删除
        uUserMapper.deleteByPrimaryKey(uid);

        //根据用户id 条件删除中间表
        RoleUserExample example = new RoleUserExample();
        RoleUserExample.Criteria criteria = example.createCriteria();
        criteria.andUidEqualTo(uid);
        roleUserMapper.deleteByExample(example);
    }

}
